package app

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)

//自定义验证提示
var NotPage = map[string]string{
	"NotPageAndLimit": "当前参数不正确！",
}

var (
	uni      *ut.UniversalTranslator
	validate *validator.Validate
	trans    ut.Translator
)

//自定义验证
var NotPageAndLimit validator.Func = func(fl validator.FieldLevel) bool {
	fmt.Println(`当前执行了验证器！`)
	if val, ok := fl.Field().Interface().(int); ok {
		if val == 1 {
			fmt.Println(`当前执行了验证器！`)
			return false
		}
	}
	return true
}

func Translate(err error) string {
	var result string

	errors := err.(validator.ValidationErrors)

	for _, err := range errors {

		//判断是自定义验证方法
		var (
			tag   = err.Tag()   //绑定的验证方法
			field = err.Field() //绑定的验证字段
			msg   string
		)
		if val, exist := NotPage[tag]; exist {
			msg = field + val + ";"
		} else {
			msg = err.Translate(trans) + ";"
		}

		//if val, exist := fieldName[field]; exist {
		//	msg = strings.Replace(msg, field, val, 1)
		//}

		result += msg
	}
	return result
}

//注册 自定义验证 validator
func RegisterValidation() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("NotPageAndLimit", NotPageAndLimit)
	}
	_ = zhTranslations.RegisterDefaultTranslations(validate, trans)
}
